// manager/pages/editmerchant/index.js
import config from '../../../utils/config';
import { request, uploadFile } from '../../../utils/request';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: config.baseUrl,
        // 禁用表单
        disabled: false,
        // 行业字典
        industryList: [],
        // 业务字典
        busiList: [],
        keynoteList: [],
        // 商户标签
        merchantTag: [],
        latitude: "",
        longitude: "",
        form: {
            id: "",
            handName: "",
            headPic: "",
            coordinate: "",
            mapAddress: "",
            address: "",
            industry: "",
            businessLabel: "",
            marketingFocus: "",
            merchantLabel: "",
            licenseName: "",
            licensePic: "",
            remark: "",
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.merchantId){
            this.setData({
                ['form.id']: options.merchantId,
            })
            wx.setNavigationBarTitle({
                title: "编辑商户"
            })
            this.getMerchantInfo();
        }else{
            // 获取字典
            this.getDictionaryInfo();
            // 获取当前位置
            this.getLatLng();
        }
        
        this.initValidate();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        let { form } = this.data;
        form[key] = value;
        this.setData({
            form
        })
    },

    /**
     * 商户标签
     */
    beTag(e) {
        let { item } =  e.currentTarget.dataset;
        let arr = this.data.form.merchantLabel?this.data.form.merchantLabel.split(","):[];
        let index = arr.indexOf(item.dictValue);
        console.log(arr,arr.indexOf(item.dictValue))
        if(index == -1){
            arr.push(item.dictValue);
        }else{
            arr.splice(index,1);
        }
        this.setData({
            'form.merchantLabel': arr.join(",")
        })
    },

    // 商户信息
    getMerchantInfo(){
        request({
            url: "/merchantMarketing/getMerchantInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.id
            }
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                for(let key in form){
                    form[key] = res.data[key];
                }
                let latitude = "";
                let longitude = "";
                if(form.coordinate){
                    latitude = form.coordinate.split(",")[0];
                    longitude = form.coordinate.split(",")[1];
                }
                this.setData({
                    form,
                    latitude,
                    longitude
                })
                // 获取字典
                this.getDictionaryInfo();
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 已开通业务、营销重点选择
     */
    onCheckboxChange(e) {
        console.log(e)
        let { key, item } = e.currentTarget.dataset;
        let arr = this.data.form[key]?this.data.form[key].split(","):[];
        let index = arr.indexOf(item.dictValue);
        if(index != -1){
            arr.splice(index,1);
        }else{
            arr.push(item.dictValue);
        }
        this.setData({
            ['form.'+key]: arr.join(",")
        });
        if(key == "businessLabel"){
            this.getKeynoteList(this.data.busiList);
        }
    },

    // 查看图片
    previewImage(e) {
        let { url } = e.currentTarget.dataset;
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: [url] // 需要预览的图片http链接列表
        })
    },

    /**
     * 获取所属行业、营销重点、商户标签字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType: "ecard_merchant_industry"
			}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    industryList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "ecard_merchant_business_tag"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    busiList: res.data
                })
                this.getKeynoteList(res.data);
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "ecard_merchant_tag"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    merchantTag: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 获取营销重点
    getKeynoteList(list){
        let keynoteList = [];
        let arr = this.data.form.businessLabel?this.data.form.businessLabel.split(","):[];
        let farr = this.data.form.marketingFocus?this.data.form.marketingFocus.split(","):[];
        
        list.forEach(item => {
            if(arr.indexOf(item.dictValue)==-1){
                keynoteList.push(item)
            }
        })
        arr.forEach(item => {
            let index = farr.indexOf(item);
            if(index != -1){
                farr.splice(index,1);
            }
        })
        console.log(farr)
        this.setData({
            keynoteList,
            ['form.marketingFocus']: farr.join(",")
        })
    },

    // 调整定位
    fineLocation(e){
        let that = this;
        wx.chooseLocation({
            latitude: this.data.latitude,
            longitude: this.data.longitude,
            scale: 18,
            success(res){
                console.log(res)
                let latitude = res.latitude;
                let longitude = res.longitude;
                request({
                    url: `/merchantMarketing/calculateDistance`,
                    reqRSAENCRY: true, // 参数是否加密
                    resRSADECRY: false, // 返回值是否解密
                    data: {
                        coordinate: `${that.data.latitude},${that.data.longitude}`,
                        chooseCoordinate: `${latitude},${longitude}`,
                    }
                }).then(res => {
                    if(res.code == 0){
                        that.setData({
                            latitude,
                            longitude
                        })
                        that.getCoordinatePositionInfo(latitude,longitude)
                    }
                }).catch(error => {
                    // console.log(error)
                })
            }
        })
    },
    
    // 获取经纬度
    getLatLng(){
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.log(res)
                if (res.authSetting['scope.userLocation'] == false) {//非初始化进入该页面,且未授权
                    wx.showModal({
                        title: '是否授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: function (data) {
                                        // console.log(data);
                                        if (data.authSetting["scope.userLocation"] == true) {
                                            that.getLocation();
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else {//初始化进入
                    // console.log("KKKKK") 
                    that.getLocation();
                }
            }
        })
    },
    getLocation(){
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success (res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                })
                that.getCoordinatePositionInfo(res.latitude,res.longitude)
            },
            complete: function(res) {
                console.log(res)
                if(res.errMsg == "getLocation:fail auth deny"){
                    // wx.showToast({
                    //     title: '获取定位失败',
                    //     icon: 'none',
                    //     duration: 2000
                    // });
                }
            }
        })
    },
    getCoordinatePositionInfo(latitude,longitude){
        // const that = this;
        let { form } = this.data;
        request({
            url: "/commonApi/getCoordinatePositionInfo",
            method: "GET",
            data: {
                coordinate: `${latitude},${longitude}`
            }
        }).then(res => {
            if(res.code == 0){
                form.coordinate = `${latitude},${longitude}`;
                form.mapAddress = res.data.address;
                form.address = res.data.address;
                this.setData({
                    form
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 商户图片或营业执照图片上传
    uploadImage(e) { // 拍摄或从相册选取上传
        let { key } = e.currentTarget.dataset;
        let that = this;
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success(res) {
                wx.compressImage({
                    src: res.tempFilePaths[0], // 图片路径
                    quality: 40, // 压缩质量
                    success(res1) {
                        uploadFile({
                            url: "/commonApi/imageUploadAddWatermark",
                            filePath: res1.tempFilePath,
                            name: "imgfile",
                            formData: {
                                coordinate: that.data.form.coordinate,
                                watermark: that.data.form.mapAddress,
                                fileName: key
                            }
                        }).then(res => {
                            if(res.code == 0){
                                that.setData({
                                    ['form.'+key]: res.data
                                })
                            }
                        }).catch(error => {
                            // console.log(error)
                        })
                    }
                })
            }
        })
    },
    // 保存
    save(e) {
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        request({
            url: `/merchantMarketing/addMerchantInfo`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                setTimeout(()=>{
                    wx.navigateBack()
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            handName: {
                required: true
            },
            headPic: {
                required: true
            },
            coordinate: {
                required: true
            },
            address: {
                required: true
            },
            industry: {
                required: true
            },
            businessLabel: {
                required: true
            },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            handName: {
                required: '请输入门面名称'
            },
            headPic: {
                required: '请上传门面图片'
            },
            coordinate: {
                required: '地图位置'
            },
            address: {
                required: '请输入详细地址'
            },
            industry: {
                required: '请选择所属行业'
            },
            businessLabel: {
                required: '请选择已开通业务'
            },
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})